package com.hmall.item.listener;

import cn.hutool.json.JSONUtil;
import com.hmall.item.domain.po.ItemDoc;
import lombok.extern.slf4j.Slf4j;
import org.apache.http.HttpHost;
import org.elasticsearch.action.index.IndexRequest;
import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.client.RestClient;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.common.xcontent.XContentType;
import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.BeforeEach;
import org.springframework.amqp.rabbit.annotation.Exchange;
import org.springframework.amqp.rabbit.annotation.Queue;
import org.springframework.amqp.rabbit.annotation.QueueBinding;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.stereotype.Component;

import java.io.IOException;

@Component
@Slf4j
public class itemEsListener {

    private RestHighLevelClient client;

    @BeforeEach
    void setUp() {
        this.client = new RestHighLevelClient(RestClient.builder(
                HttpHost.create("http://8.154.20.117:9200")
        ));
    }

    @RabbitListener(bindings = @QueueBinding(
            value = @Queue("itemEs.queue"),
            exchange = @Exchange(name = "itemEs.direct"),
            key = {"addItemToEs"}
    ))
    public void saveItemToEs(String itemStr) throws IOException {
        ItemDoc itemDoc = JSONUtil.toBean(itemStr, ItemDoc.class);
        IndexRequest request = new IndexRequest("items").id(itemDoc.getId());
        request.source(itemStr, XContentType.JSON);
        client.index(request, RequestOptions.DEFAULT);
    }


    @AfterEach
    void tearDown() throws IOException {
        this.client.close();
    }
}
